<template>
  <el-upload class="upload-demo" :action="'/back-api/pc/upload/uploadFile/'" :show-file-list="false" :headers="headers"
    name="file" list-type="text" :on-success="upSuccess" :before-upload="beforeUploadBanner">
    <div class="flex up" :style="'width: ' + width + 'px;' + 'height:' + height + 'px;'">
      <img class="imgUrl" v-if="imgUrl" :src="imgUrl" alt=""
        :style="'width: ' + width + 'px;' + 'height:' + height + 'px;'" />
      <i v-else class="el-icon-upload upIcon"></i>
    </div>
  </el-upload>
</template>
<script>
export default {
  name: "ImgUpload",
  props: {
    para: { type: String, default: "" },
    width: { type: String, default: "280" },
    height: { type: String, default: "130" },
    imgUrl: { type: String, default: "" },
  },
  computed: {
    headers() {
      return {
        Authorization: window.localStorage.getItem("token"),
      };
    },
  },
  methods: {
    upSuccess(res) {
      if (res.code == 200) {
        this.$message({
          showClose: true,
          message: res.msg,
          type: "success",
        });
        this.$emit("setImg", res.data, this.para);
      } else {
        this.$message({
          showClose: true,
          message: res.msg,
          type: "error",
        });
      }
    },
    // 上传前
    beforeUploadBanner(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
  },
};
</script>
<style lang="less" scoped>
.upload-demo {
  .up {
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;

    .upIcon {
      color: #999;
      font-size: 50px;
    }

    .imgUrl {
      border-radius: 5px;
    }
  }
}
</style>